<?php

namespace App\Http\Controllers\lxSystem;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Models\Brand;

use Illuminate\Support\Facades\Validator;
class BrandController extends Controller
{
    function index(Request $request){
        $where = function ($query) use ($request) {
            if ($request->has('keyword') and $request->keyword != '') {
                $search = "%" . $request->keyword . "%";
                $query->where('name', 'like', $search);
            }
        };
        //return config('lxSystem.page_size');
       $brands=Brand::where($where)->orderBy('sort_order')->paginate(env('PAGE_SIZE'));
       return view('lxSystem.brands.index')->with('brands',$brands);
    }

    function create(){
        return view('lxSystem.brands.create');
    }
    
    function store(Request $request){

        $this->validate($request, [
            'name' => 'required|unique:brands,name|max:45',
            //'desc' => 'required',
        ]);
////
////        $messages = Validator::errors();
////        $messages = [
////            'required' => ':attribute field is required.',
////        ];
//
//        $validator=Validator::make($request->all(), [
//            'name' => 'required|unique:brands,name|max:45',
//            'desc' => 'required',
//        ], [
//            'required' => ':attribute 必须填写',
//            'unique' => ':attribute 不能重复',
//        ]);
//        if ($validator->fails()) {
//            return redirect('post/create')
//                ->withErrors($validator)
//                ->withInput();
//        }
        Brand::create($request->all());
        return redirect(route('brands.index'));
    }
    
    function edit($id){
        $brand=Brand::find($id);
        //return $brand;
        return view('lxSystem.brands.edit')->with('brand',$brand);
    }
    
    function update(Request $request,$id){
       $brand=Brand::find($id);
        $brand->update($request->all());
        return redirect(route('brands.index'));
    }

    function destroy($id){
        Brand::destroy($id);
        return redirect(route('brands.index'))->with('error', '删除成功!');
    }
//    function show($id){
//        Brand::destroy($id);
//        return redirect(route('brands.index'))->with('error', '删除成功!');
//    }

    function sort_order(Request $request){
        $brand=Brand::find($request->id);
        $brand->sort_order=$request->sort_order;
        $brand->save();
    }

    function is_something(Request $request){
        $brand=Brand::find($request->id);
        $value = $brand->is_show ? false : true;
        $brand->is_show = $value;
        $brand->save();
    }
    
    function copy($id){
        $brand=Brand::find($id);
        Brand::create(collect($brand)->forget(['id','created_at','updated_at'])->all());
        return redirect(route('brands.index'));
    }
}
